from view.baseview import BaseView
from orm.model import Position, db, PositionApp, AllApp


class AuthorityManagementView(BaseView):
    '''
        部门权限管理
        参数：BsseView：  对返回参数的操作类
    '''

    def query(self, queryForm):
        '''
            获取后台数据库数据(获取职位信息)
            :return: 查询的数据列表
        '''
        print(queryForm)

        if queryForm['position']['id'] == "" or queryForm['position']['id'] == None:
            sql = """
                SELECT
                    id,
                    name 
                FROM
                    position
            """
            # 执行sql语句：查询职位
            positions = AllApp.raw(sql)

            data_position = []
            # 循环职位列表
            for position in positions:
                data_position.append({"id": position.id, "name": position.name})

            print(data_position)
            result = {"data": [], "data_position": data_position}
            return super().resultSet(200, "职位查询成功！", result)

        sql = """
            SELECT
                id,
                text,
                imgsrc
            FROM
                allapp
            WHERE
                group_id = 1 
                or group_id = 2 
        """
        # 执行sql语句:查询应用
        allapps = AllApp.raw(sql)

        sql = """
            SELECT
                id,
                position_id,
                app_id
            FROM
                positionapp
            """
        # 执行sql语句：查询职位与应用关系
        positionapps = AllApp.raw(sql)

        data = []
        # data_dict = {"name": position.name, "data": []}
        allappId = 0  # 标记每个应用排列顺序
        # 循环应用列表
        for allapp in allapps:

            # print(type(allapp.id), allapp.id, type(allapp.text), allapp.text, type(allapp.imgsrc), allapp.imgsrc);
            isBoolean = True  # 查看这个职位是否有此应用的权限

            # 循环职位与应用对应列表
            for positionapp in positionapps:

                # print(type(positionapp.id), positionapp.id, type(positionapp.position_id), positionapp.position_id,
                #       type(positionapp.app_id), positionapp.app_id);

                if queryForm['position']['id'] == positionapp.position_id:
                    if allapp.id == positionapp.app_id:
                        data.append({"id": allappId, 'name': allapp.text,
                                     'imgsrc': allapp.imgsrc, 'jurisdiction': True,
                                     "positionapp_id": positionapp.id, "position_id": positionapp.position_id,
                                     "app_id": positionapp.app_id})
                        isBoolean = False
            if isBoolean:
                data.append({"id": allappId, 'name': allapp.text,
                             'imgsrc': allapp.imgsrc, 'jurisdiction': False,
                             "positionapp_id": 0, "position_id": queryForm['position']['id'],
                             "app_id": allapp.id})

            allappId += 1

        print(data)

        """
            [{"name":"销售总监",data:[{"id":0,"name":"用户管理1",'imgsrc':'../desktop/icon/icon2.png','jurisdiction':true},
            {"id":1,"name":"我的通知1",'imgsrc':'../desktop/icon/notify.png','jurisdiction':false},
            {"id":2,"name":"工商注册1",'imgsrc':'../desktop/icon/gongshang.png','jurisdiction':true},
            {"id":3,"name":"销售团队1",'imgsrc':'../desktop/icon/gongshang.png','jurisdiction':true}]},
            {"name":"销售主管",data:[{"id":0,"name":"用户管理2",'imgsrc':'../desktop/icon/icon2.png','jurisdiction':false},
            {"id":1,"name":"我的通知2",'imgsrc':'../desktop/icon/notify.png','jurisdiction':true},
            {"id":2,"name":"工商注册3",'imgsrc':'../desktop/icon/gongshang.png','jurisdiction':false},
            {"id":3,"name":"销售团队4",'imgsrc':'../desktop/icon/gongshang.png','jurisdiction':false}]}]

            data = [{"name":"销售总监","用户管理":"","我的通知":"","工商注册":true,"我的客户":false},{"name":"销售主管","用户管理":"","我的通知":"","工商注册":false,"我的客户":true}]
			commonlyUsed = [{'name':'用户管理','imgsrc':'../desktop/icon/icon2.png'},{'name':'我的通知','imgsrc':'../desktop/icon/notify.png'}],//常用栏
            desktop = [{'name':'工商注册','imgsrc':'../desktop/icon/gongshang.png'},{'name':'我的客户','imgsrc':'../desktop/icon/mycustomer.png'}],//桌面
        """

        result = {"data": data, "data_position": []}
        return super().resultSet(200, "查询成功！", result)

    def update(self, data):
        '''
            根据前台数据修改数据库信息（增添或删除）
            : data 参数 （职位及其对应的应用有无信息）
        '''

        if data['positionapp_id'] == 0:
            if data['jurisdiction']:

                PositionApp.create(position_id=data['position_id'], app_id=data['app_id'])

                sql = """
                    SELECT
                        id,
                        position_id,
                        app_id
                    FROM
                        positionapp
                    WHERE
                        position_id = {0} 
                        AND app_id = {1}
                """.format(data['position_id'],data['app_id'])
                # 执行sql语句：查询职位与应用关系
                positionapps = PositionApp.raw(sql)

                if len(positionapps) != 0:
                    data['positionapp_id'] = positionapps[0].id
                else:
                    data['jurisdiction'] = False
                    result = {"data": data}
                    return super().resultSet(201, "修改出错！", result)
        else:
            if data['jurisdiction'] == False:
                PositionApp.delete().where(PositionApp.id == data['positionapp_id']).execute()

                sql = """
                    SELECT
                        id,
                        position_id,
                        app_id
                    FROM
                        positionapp
                    WHERE
                        id = {0}
                """.format(data['positionapp_id'])
                # 执行sql语句：查询职位与应用关系
                positionapps = PositionApp.raw(sql)

                if len(positionapps) == 0:
                    data['positionapp_id'] = 0
                else:
                    data['jurisdiction'] = True
                    result = {"data": data}
                    return super().resultSet(201, "删除出错！", result)

        result = {"data": data}
        return super().resultSet(200, "修改成功！", result)

    def insert(self,value):
        '''
            根据前台数据增加数据库position表信息（增添或删除）
            : value 参数 （职位名）
        '''

        position = Position.create(name=value['value'])
        if position.id != 0:
            sql = """
                SELECT
                    id,
                    name 
                FROM
                    position
            """
            # 执行sql语句：查询职位
            positions = AllApp.raw(sql)

            data_position = []
            # 循环职位列表
            for position in positions:
                data_position.append({"id": position.id, "name": position.name})

            print(data_position)
            result = {"data": [], "data_position": data_position}
            return super().resultSet(200, "查询成功！", result)

    @db.atomic()
    def deletet(self,row):
        '''
            根据前台数据删除数据库position表信息（删除）
            : row 参数 （职位名及职位id）
            @db.atomic() : 事务提交
        '''

        Position.delete().where(Position.name == row['name']).execute()
        PositionApp.delete().where(PositionApp.position_id == row['id']).execute()

        sql = """
            SELECT
                id,
                name 
            FROM
                position
        """
        # 执行sql语句：查询职位
        positions = AllApp.raw(sql)

        data_position = []
        # 循环职位列表
        for position in positions:
            data_position.append({"id": position.id, "name": position.name})
            if position.name == row['name']:
                return Exception

        print(data_position)
        result = {"data": [], "data_position": data_position}
        return super().resultSet(200, "删除成功！", result)



